package com.bluejazz.validator;

import com.bluejazz.application.dto.SalarySlipDTO;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import java.math.BigDecimal;
import java.util.Objects;

public class SalaryValidator implements Validator {
    @Override
    public boolean supports(Class<?> clazz) {
        return clazz == SalarySlipDTO.class;
    }

    @Override
    public void validate(Object o, Errors errors) {
        if (Objects.isNull(o)) {
            errors.rejectValue("", null, "工资不能为空");
            return;
        }
        SalarySlipDTO salarySlipDTO = (SalarySlipDTO)o;
        BigDecimal sumUp = salarySlipDTO.getDetails().stream().reduce(new BigDecimal("0"), BigDecimal::add);
        if (!salarySlipDTO.getTotalAmount().equals(sumUp)) {
            errors.rejectValue("totalAmount", null, "工资明细和总数对不上"); // 1st param is the property name of SalarySlipDTO
        }
    }
}
